#!/bin/sh /etc/rc.common

USE_PROCD=1
START=99

CONF="qbittorrent"
PROG="/usr/bin/qbittorrent-nox"

QBT_CONF="/etc/qBittorrent/config/qBittorrent.conf"
QBT_LOG="/var/log/$CONF"

start_service() {
	config_load "$CONF"

	local enabled
	config_get_bool enabled "config" "enabled" "0"
	[ "$enabled" -eq "1" ] || return 1

	local download_dir http_port
	config_get download_dir "config" "download_dir" "/mnt/sda1"
	config_get http_port "config" "http_port" "8080"

	[ -d "$download_dir" ] || mkdir -p "$download_dir"

	if [ -f "$QBT_CONF" ]; then
		sed -e "s,WebUI\\\Port=[0-9]*,WebUI\\\Port=$http_port,g" \
		    -e "s,Session\\\DefaultSavePath=.*,Session\\\DefaultSavePath=$download_dir,g" \
			-i "$QBT_CONF"
	else
		mkdir -p "${QBT_CONF%/*}"
		cat > "$QBT_CONF" <<-EOF
		[Application]
		FileLogger\Path=$QBT_LOG

		[AutoRun]
		enabled=false
		program=

		[BitTorrent]
		Session\AutoBanUnknownPeer=true
		Session\AutoUpdateTrackersEnabled=true
		Session\DefaultSavePath=$download_dir

		[LegalNotice]
		Accepted=true

		[Network]
		Cookies=@Invalid()

		[Preferences]
		Bittorrent\CustomizeTrackersListUrl=https://trackerslist.com/all.txt
		WebUI\CSRFProtection=false
		WebUI\Password_PBKDF2="@ByteArray(zH92gnE9xijRN5IjzIPU+A==:+JxpKBWsSyuzpm/9LrhO2uLQSGsBS5giqF0AYRU8COcMXn5AIaSsL2S9hIuB20wkhsMfEoN+77Q9BmAd3ysYxw==)"
		WebUI\Port=$http_port
		EOF
	fi

	procd_open_instance
	procd_set_param command "$PROG"
	procd_append_param command "--profile=/etc"

	procd_set_param limits core="unlimited"
	procd_set_param limits nofile="1000000 1000000"
	procd_set_param respawn
	procd_set_param stderr 1

	procd_close_instance
}

stop_service() {
	rm -rf "$QBT_LOG"
}

service_triggers() {
	procd_add_reload_trigger "$CONF"
}
